<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Utils;

use App\Constants\ErrorCode;

class Jwt
{
    private $tokenKey;

    private $tokenExpire;

    public function __construct()
    {
        $this->tokenKey = config('jwt_token_key');
        $this->tokenExpire = config('jwt_token_expire');
    }

    /**
     * jwt加密.
     * @param $data
     */
    public function encode($data): string
    {
        $time = time();
        $expireTime = $this->tokenExpire;
        $expireTime = $time + $expireTime;
        $refreshTime = $expireTime - 60 * 60;
        $payload = [
            'iat' => $time, //token签发时间
            'nbf' => $time, //token生效时间 即时生效
            'exp' => $expireTime, //token过期时间
            'refresh_time' => $refreshTime, //token可刷新时间
        ];
        $payload = array_merge($payload, $data);
        return \Firebase\JWT\JWT::encode($payload, $this->tokenKey);
    }

    /**
     * 解析token.
     * @param $token
     */
    public function checkToken($token): array
    {
        $isOk = false;
        $errorCode = ErrorCode::PARAM_ERROR;
        $tokenKey = $this->tokenKey;
        $tokenData = [];
        try {
            $tokenObj = \Firebase\JWT\JWT::decode($token, $tokenKey, ['HS256']);
            $tokenData = (array) $tokenObj;
            $expireTime = $tokenData['exp'];
            if (time() > $expireTime) {
                $errorCode = ErrorCode::LOGIN_TIMEOUT;
            }
            $isOk = true;
        } catch (\Exception $e) {
            $errorCode = ErrorCode::NOT_LOGIN;
        }
        return [
            'is_ok' => $isOk,
            'code' => $errorCode,
            'data' => $tokenData,
        ];
    }
}
